var express = require('express');
var mongoose = require('mongoose');
var async = require('async');
var url = require('url');
var mongoose = require('mongoose');
var util = require('../models/util');


require('../models/user.js');
require('../models/category.js');
require('../models/store.js');
require('../models/battle.js');
require('../models/letter.js');

var User = mongoose.model('User');
var Category = mongoose.model('Category');
var Store = mongoose.model('Store');
var Battle = mongoose.model('Battle');
var Letter = mongoose.model('Letter');

var router = express.Router();

//获取当前用户接收到得消息
router.post('/inbox', function (req, res) {
    var query = req.query;
    console.log(query);
    var skip = query.skip;
    var limit = query.limit;
    //var user = req.session.user;
    var userId = query.userId;
    Letter.find({
        receiver: userId
    }).sort({
        time: 'desc'
    }).populate('sender').populate('receiver').populate('store').skip(skip).limit(limit).exec(function (err, letters) {
        if (err) throw err;
        letters = util.toJSON(letters);
        res.send(letters);
    });
});

//我发送的挑战信
router.post('/outbox', function (req, res) {

    var query = req.query;
    console.log(query);
    var skip = query.skip;
    var limit = query.limit;
    //var user = req.session.user;
    var userId = query.userId;
    Letter.find({
        sender: userId
    }).sort({
        time: 'desc'
    }).populate('sender').populate('receiver').populate('store').skip(skip).limit(limit).exec(function (err, letters) {
        if (err) throw err;
        letters = util.toJSON(letters);
        res.send(letters);
    });
});

/**
 *
 */
router.post('/queryuser', function(req, res){
    var query = req.query;
    console.log(query);
    var name = query.name;
    User.find({
        name : new RegExp(name)
    }).limit(5).exec(function(err, data){
        if(err) throw err;
        console.log(data);
        res.send(data);
    })
});

//发送挑战信
router.post('/send', function(req, res){
    var query = req.query;
    console.log(query);
    var receivers = query.receivers;
    if(!(receivers instanceof Array)){
        receivers = [].concat(receivers);
    }
    var userId = query.userId;
    var storeId = query.storeId;
    var text = query.text;
    var letters = [];
    for(var i = 0, len = receivers.length; i < len; i++){
        var letter = new Letter({
            sender: userId, //发送人
            receiver: receivers[i], //收件人
            text: text, //内容
            status: 'N',  //挑战状态：N - 未读 F - 已读
            time: new Date()
        });
        if(storeId){
            letter.store = storeId;
        }
        letters.push(letter);
    }
    async.eachSeries(letters, function(letter, callback){
        console.log('sending... ' + letter);
        letter.save(function(err, data){
            callback(err, data);
        });
    }, function(err, data){
        if(err) throw err;
        res.send({
            SUCC : true
        });
    });
});

//删除信件
router.post('/delete', function(req, res){
    var query = req.query;
    console.log(query);
    var letterId = query.letterId;
    Letter.findByIdAndRemove(letterId,{}, function(err){
        if(err) throw err;
        res.send({
            SUCC : true
        });
    });
});

module.exports = router;
